<template>
	<view id="edit_add_brs">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view class="body">
			<view class="title">{{title}}</view>
			<view class="top">
				<button @click="formSubmit" style="margin: 0;" size="mini">{{$t('global.button.sure')}}</button>
			</view>
			<scroll-view class="form_warpper" scroll-y="true">

				<uni-forms validateTrigger="bind" :modelValue="formdata" :rules="rules" ref="bagRunesForm">

					<uni-forms-item name="runes" :label="$t('home.form.runes.label')">
						<uni-easyinput :clearable="true" type="textarea" v-model="formdata.runes"
							:placeholder="$t('home.form.runes.placeholder')" />
					</uni-forms-item>

					<view class="run-img-list">
						<template v-for="(data,index) in curInputRune">
							<view class="item_wrapper" :key="'show-rune'+ index">
								<view class="img-box">
									<image :src="'/static/img' + data.rune.src" mode="aspectFit"></image>
								</view>
								<view class="num">{{data.num == -1 ? '?': data.num}}</view>
							</view>
						</template>
					</view>


				</uni-forms>
			</scroll-view>
		</view>

	</view>
</template>

<script>
	/**
	 *  uni_forms 文档 https://uniapp.dcloud.net.cn/component/uniui/uni-forms.html#%E4%BB%8B%E7%BB%8D
	 * uni_modules 官方组件所有需自己导入列表:  https://uniapp.dcloud.net.cn/component/uniui/quickstart.html#%E9%80%9A%E8%BF%87-uni-modules-%E5%8D%95%E7%8B%AC%E5%AE%89%E8%A3%85%E7%BB%84%E4%BB%B6
	 * 	uni_forms： https://ext.dcloud.net.cn/plugin?name=uni-forms
	 *  uni-easyinput https://ext.dcloud.net.cn/plugin?name=uni-easyinput
	 *  uni-data-checkbox https://ext.dcloud.net.cn/plugin?id=3456
	 * */
	import $validate_ from '@/utils/validate.js';
	import $cst_ from '@/utils/constant.js'
	import $utils_ from '@/utils/common.js'


	import RUNEWORDS_DATA from "@/data/runewords.js";
	import RUNES_DATA from "@/data/runes.js";
	export default {
		data() {
			const _this = this;
			return {
				title: _this.$t("home.form.title.add_bag_runes"),
				formType: $cst_.OPS.ADD,
				curInputRune: [], // 解析输入runes对应数据
				original_data: {},
				// @todo num-of-slots
				formdata: {
					runes: '',
				},
				rules: {
					runes: {
						rules: [{
								required: true,
								errorMessage: _this.$t('rune.runewords.form.runes.valid.required'),
							},
							{
								validateFunction: (rule, value, data, callback) => {
									let runes_class_num = _this.runes.length;
									let reg1 = /^[a-zA-Z]+[0-9]*(,[a-zA-Z]+[0-9]*)*$/; // 格式校验(字母数字,)
									let reg2 = /^[a-zA-Z]{1,5}[0-9]*(,[a-zA-Z]{1,5}[0-9]*)*$/; // 符石名称校验
									let reg3 = new RegExp(
										`^[a-zA-Z]{1,5}[0-9]*(,[a-zA-Z]{1,5}[0-9]*){0,${runes_class_num-1}}$`,
										'g'
									); // 符石类别数量校验
									let reg4 = /^[a-zA-Z]{1,5}[1-9](,[a-zA-Z]{1,5}[1-9])*$/; // 符石对应数量校验

									// console.log("111", value);

									if (!reg1.test(value)) {
										// console.log("1123",value);
										return callback(_this.$t('home.form.runes.valid.input_format'));
									} else if (!reg2.test(value)) {
										return callback(_this.$t(
											'home.form.runes.valid.rune_name_length'));
									} else if (!reg3.test(value)) {
										return callback(_this.$t(
											'home.form.runes.valid.out_rune_total'));
									} else {
										// console.log("222", value);
										let reg_rune_name = /^[a-zA-Z]{1,5}[0-9]$/;


										let runes = value.split(",");
										let data_f = runes.map(el => {

											let num = -1;
											let name = el;
											if (reg_rune_name.test(el)) {
												num = parseInt(el.substr(el.length - 1));
												name = el.substr(0, el.length - 1);
											}
											// console.log(num, name);
											return {
												name: name,
												name_u: name.toUpperCase(),
												num,
												rune: null,
											};
										}); // 输入信息格式化


										if (data_f.length > 1) {
											// 输入符石重复校验
											for (let i = 0; i < data_f.length - 1; i++) {
												for (let j = i + 1; j < data_f.length; j++) {
													// console.log(i, j, data_f[i], data_f[j], data_f[i].toUpperCase(), runes[j].toUpperCase());
													if (data_f[i].name_u === data_f[j].name_u) {
														return callback(data_f[i].name + " " + _this.$t(
															'home.form.runes.valid.rune_repeat'));
													}
												}
											}
										}


										// console.log("223", value);

										// 符石存在判断
										for (let i = 0; i < data_f.length; i++) {
											let name = data_f[i].name_u;
											// if (!RUNES_DATA.some(el => el.name === name)) {
											let rune = _this.runesMap.get(name);
											if (!rune) {
												return callback(data_f[i].name + " " + _this.$t(
													'home.form.runes.valid.abset'));
											}

											data_f[i].rune = rune;
										}

										// 展示符石图片
										_this.$nextTick(() => {
											_this.curInputRune = $utils_.JSONParse($utils_.JSONStringify(
												data_f));
										});

										// console.log("224", value);
										// 符石对应数量校验
										if (!reg4.test(value)) {
											return callback(_this.$t(
												'home.form.runes.valid.rune_num'));
										}





									}
									// console.log("333");
									callback();
								}
							},



						],
					},
					// form-item runes&rules end...


				},

				// data rules end...


				runes: RUNES_DATA,

				/**@type{Map<string,import('@/data/runes.js').Rune}>} @todo 应该使用vux或者全局变量*/
				runesMap: new Map(),
			};
		},


		watch: {
			["formdata.runes"](newVal, oldVal) {
				// console.log(newVal, oldVal);
				if (newVal === "") {
					this.$nextTick(() => {
						this.curInputRune = [];
					})
				}
			}
		},

		created() {
			// console.log('执行了created。。。');
			const _this = this;

			_this.runes.forEach((val) => {
				let rune = val;
				this.runesMap.set(val.name, val);
			});

			// console.log(_this.user_runewords)

			// _this.$utils_.testJSONPS();
			// uni.$once("test", (res) => {
			// 	console.log("res", res);
			// });
		},
		onLoad(option) {
			const _this = this;
			// console.log('执行了onLoad...', option);
			const eventChannel = _this.getOpenerEventChannel();
			// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
			eventChannel.once('acceptDataFromOpenerPage', (res) => {
				// console.log("acceptDataFromOpenerPage", res);
				if (res.type == $cst_.OPS.ADD) {
					_this.formType = $cst_.OPS.ADD;
					_this.title = _this.$t("home.form.title.add_bag_runes");
				} else if (res.type == $cst_.OPS.SET) {

					_this.formType = $cst_.OPS.SET;
					_this.title = _this.$t("home.form.title.set_bag_runes");

					_this.original_data = res.data;

					_this.formdata.runes = res.data.map(el => el.name + el.num).join();

					_this.$nextTick(() => {
						_this.curInputRune = res.data.map(el => {
							return {
								name: el.name,
								name_u: el.name,
								num: el.num,
								rune: el.rune,
							}
						});
					});
				}

			});
		},
		methods: {

			formSubmit: $utils_.debounce(function(el) {
				let _this = this;
				// console.log("formSubmit");
				_this.$refs.bagRunesForm.validate().then((res) => {
					// 成功返回，res 为表单数据
					// console.log(_this.$utils_.JSONStringify(_this.formdata), res);
					// console.log(_this.curInputRune);

					// console.log(_this.formType);
					if (_this.formType == $cst_.OPS.ADD) {
						try {

							// throw new Error("test");
							let data = _this.curInputRune.map(el => {
								return {
									name: el.name_u,
									num: el.num,
								}
							});

							uni.setStorageSync($cst_.KEY_OF_BAG_RUNES,
								_this.$utils_.JSONStringify(data));

							console.log("添加成功");
							// 添加成功
							uni.navigateBack({
								success(res) {

									console.log("添加成功返回到上一页");
									// 刷新数据
									uni.showToast({
										title: _this.$t(
											'global.note.add_success'),
										image: '/static/img/toast/success.png',
										duration: 1000
									});
									uni.$emit('refresh_bag_runes');
								}
							});
						} catch (err) {
							console.error("add err", err);
							uni.showToast({
								title: _this.$t(
									'global.note.add_failed'),
								image: '/static/img/toast/failure.png',
								duration: 2000
							});
						}

					} else if (_this.formType == $cst_.OPS.SET) {

						try {
							// throw new Error("test");
							let data = _this.curInputRune.map(el => {
								return {
									name: el.name_u,
									num: el.num,
								}
							});


							uni.setStorageSync($cst_.KEY_OF_BAG_RUNES,
								_this.$utils_.JSONStringify(data));

							console.log("修改成功");
							// 修改成功
							uni.navigateBack({
								success(res) {

									console.log("修改成功返回到上一页");
									// 刷新数据
									uni.showToast({
										title: _this.$t(
											'global.note.set_success'),
										image: '/static/img/toast/success.png',
										duration: 1000
									});
									uni.$emit('refresh_bag_runes');
								}
							});

						} catch (err) {
							console.error("set err", err);
							uni.showToast({
								title: _this.$t(
									'global.note.set_failed'),
								image: '/static/img/toast/failure.png',
								duration: 2000
							});
						}

					}

				}).catch((err) => {
					console.error(err);
					// 表单校验验失败，err 为具体错误信息
					// 其他逻辑处理
					uni.showToast({
						title: _this.$t('global.validate.error'),
						image: '/static/img/toast/error.png',
						duration: 500
					});
				});
			}, 500, true),



		}

	}
</script>
<style lang="scss">
	#edit_add_brs {
		height: 100%;

		background-color: rgb(28, 28, 28);
		// background-color: pink;

		.status_bar {
			position: fixed;
			top: 0;
			height: var(--status-bar-height);
			width: 100%;

			// background-color: blue;
			// background-color: #f5f5f5; // 防透视.data_area
			background-color: rgb(28, 28, 28);
			z-index: 99;
		}

		.body {
			height: calc(100% - var(--status-bar-height));
			padding-top: var(--status-bar-height);
			box-sizing: border-box;
			width: 100%;
			display: flex;
			flex-direction: column;

			.title {
				text-align: center;
				height: 60rpx;
				line-height: 60rpx;
				font-weight: 700;
				color: white;
			}


			.top {
				padding: 40rpx;
				display: flex;
				box-sizing: border-box;
				height: 80rpx;
				justify-content: flex-end;
				align-items: center;
				border-bottom: 2rpx dashed #d3d3d3;
			}

			.form_warpper {
				.uni-forms {
					// height: 10000rpx;
					padding: 10rpx 20rpx calc(var(--window-bottom) + 10rpx);
					box-sizing: border-box;

					.uni-forms-item {
						margin-bottom: 44rpx;
					}

					.unlock_checkbox {
						top: 50%;
						transform: translateY(-50%);
					}

					.run-img-list {
						display: flex;
						padding-left: 130rpx;
						// margin-bottom: 44rpx;
						margin-bottom: 20rpx;
						// background-color: yellow;
						box-sizing: border-box;
						width: 100%;
						height: auto;
						// min-height: 0;
						// flex: 1;
						flex-wrap: wrap;

						// background-color: yellow;
						.item_wrapper {

							// background-color: pink;
							width: 80rpx;

							.img-box {
								margin-right: 20rpx;
								height: 80rpx;
								width: 80rpx;

								uni-image {
									height: 100%;
									width: 100%;
								}
							}

							.num {
								color: deeppink;
								font-weight: 700;
								font-size: 36rpx;
								text-align: center;
								line-height: 48rpx;
								margin: 10rpx 0;
								// background-color: gray;
							}
						}
					}
				}


				// 避免子元素撑起它
				flex: 1;
				min-height: 0;
				overflow: visible;
				// background-color: yellow;

			}
		}
	}
</style>